﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using System.Collections.Specialized;
using MarginTrading.Entity;
using MarginTrading.Services;
using System.Globalization;
using System.Threading;

namespace MarginTrading.Forms
{
    public partial class HQDataLoading : Form
    {
        
        String TrHdrFile = "Headers\\ats2_ttr.hdr";       
        String CDSTranHdrFile = "Headers\\CDS_Tran.hdr";
        String TrsumHdr = "Headers\\trsum.hdr";
        String CDSClientHdrFile = "Headers\\CDS_Regi.hdr";
        String Ins_Sect_Stat = "Headers\\Ins_Sect_Stat.hdr";

        String BROKER_CODE = "DSA";

        public HQDataLoading()
        {
            InitializeComponent();

            try
            {
                Config BrokerCodeConfig = ConfigServices.GetConfigByName("Company Code");
                BROKER_CODE = BrokerCodeConfig.Value;
               
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Database Error occurred.", "Error");
                return;
            }
           
                
        }


        private void button1_Click(object sender, EventArgs e)
        {
            Stream myStream = null;

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {

                    AtsDataTxtBox.Text = openFileDialog1.FileName;

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
         
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    TrsumFile.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message ,"Error");
                }
            }

        }



        private void CDSDataBrws_Click(object sender, EventArgs e)
        {
             OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    CDSDataTxtBox.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void Upload_Click(object sender, EventArgs e)
        {
            
            //ReadTradeHdrFile(AtsHdrTxtBox.Text);
            //ReadTradeFile();
            //CDSTranDataFile();
    
        }
        int LineWidth = 0;
        static Dictionary<String, int> mapOffset = new Dictionary<String, int>();
        static Dictionary<String, int> mapSize = new Dictionary<String, int>();



        public void ReadTradeHdrFile(String FilePath, int StartRow)
        {
            try
            {
                mapOffset.Clear();
                mapSize.Clear();
                string[] lines = System.IO.File.ReadAllLines(FilePath);
                int count = 0;
                int Offset = 0;
                System.Console.WriteLine("No of Lines :" + lines.Length);
                foreach (string line in lines)
                {
                    count++;
                    if (count < StartRow)
                        continue;

                    String ClmName = line.Substring(0, 20).Trim();
                    String size = line.Substring(32, 2);
                    int iSize = 0;
                    try
                    {
                        iSize = Int16.Parse(size);

                    }
                    catch (Exception ee)
                    {
                        continue;
                    }
                    mapSize.Add(ClmName, iSize);
                    mapOffset.Add(ClmName, Offset);

                    Console.WriteLine(ClmName + " " + iSize + " " + Offset);
                    Offset = iSize + Offset;


                }
                LineWidth = Offset;

                System.Console.WriteLine("No of ele :" + mapOffset.Count() + "   " + count);
            }
            catch (Exception fileEx)
            {
                MessageBox.Show(fileEx.Message);
            }

        }

        List<String> SymbolList = new List<String>();

        public void ReadTradeFile(String AgentCode, object sender)
        {
            try
            {
                BackgroundWorker worker = sender as BackgroundWorker;
                List<String> ExecIdCol = DailyTransactionsServices.GetExecIDCol(TrDate.Value.Date);
                List<String> ClientsList = ClientService.GetClientCodeCollection();
                SymbolList.Clear();
                SymbolList = SecurityServices.GetSecSymbolList();              

                string[] lines = System.IO.File.ReadAllLines(AtsDataTxtBox.Text);
                int count = 0;
                int AddedCount = 0;
                int DuplicatedCount = 0;
                
                //progressBar1.Value = 0;
                //progressBar1.Maximum = lines.Length;
                ThreadObj Tobj = new ThreadObj();
                Tobj.ProgressMax = lines.Length;
                Tobj.LogMsg = "Data loading - started\n";
                Tobj.increment = false;
                worker.ReportProgress(1, Tobj);

                System.Console.WriteLine("No of Lines :" + lines.Length);
             
                String[] TaxsFees = null;
                try
                {
                     TaxsFees = ConfigurationSettings.AppSettings.AllKeys;
                }
                catch(Exception er)
                {
                    MessageBox.Show("Error in App.config file. Dataloading abort !!");
                    return;
                }
                if (TaxsFees.Length == 0)
                {
                    MessageBox.Show("Error in reading config file.", "Error");
                    return;
                }
                


                foreach (string line in lines)
                {
                    count++;
                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {
                        MessageBox.Show("Error in Line " + count + " of the ats2_ttr data file.\n"+
                                       "Please check the file and try again.");
                        return;
                    }
                

                    int Quan = Int32.Parse(GetValue("quantity", line));
                    Double Price = Double.Parse(GetValue("price", line));

                    //Trading date has to be matched with the date in the file.
                    if (GetValue("trade_date", line).CompareTo(TrDate.Value.ToString("yyyy/MM/dd")) != 0 )
                    {
                        MessageBox.Show("Ats2_ttr - Trading date mismatch", "Error");
                        return;
                    }

                    ThreadObj Tobj3 = new ThreadObj();
                    Tobj3.ProgressMax = -1;
                    Tobj3.LogMsg = "";
                    Tobj3.increment = true;
                    worker.ReportProgress(1, Tobj3);

                    //progressBar1.Increment(1);
                   
                    String JointACNo = GetValue("joint_ac_no", line);
                    if (JointACNo.Length == 1)
                        JointACNo = "0" + JointACNo;

                    String ClientCode = GetValue("participant id", line) + "-" +
                                        GetValue("client_prefix", line) + "-" +
                                        GetValue("client_suffix", line) + "-" +
                                        JointACNo;
                    String CompanySymbol = GetValue("company_id", line) + "-" +
                                                                GetValue("main_type", line) + "-" +
                                                                GetValue("sub_type", line);
                   
                    //if symbol was not there in DB, it will be added.
                    UpdateSecurity(CompanySymbol);
                    
                    if (!ClientsList.Contains(ClientCode))
                    {
                        if (GetValue("buy_sell", line) == "S")
                            QuickAddClient(ClientCode, GetValue("broker_id_sell", line));
                        else
                            QuickAddClient(ClientCode, GetValue("broker_id_buy", line));

                        ClientsList.Add(ClientCode);
                        //continue;
                    }



                    String ExecID = GetValue("buy_sell", line) + GetValue("execution_id", line);
                    if (ExecIdCol.Contains(ExecID))
                    {
                        DuplicatedCount++;
                        //LogBox.AppendText("Transaction record already exist.( Exec ID -" + ExecID + " )\n");
                        continue;
                    }
                    else
                    {
                        ExecIdCol.Add(ExecID);
                    }

                    if (GetValue("status", line) != "1") //status should be 1
                    {
                        continue;
                    }
                   
                   
                      
                    Double Amount = Quan * Price;

                    double TotalTax = 0;
                    foreach (String tax in TaxsFees)
                    {
                        TotalTax = TotalTax + Double.Parse(GetValue(tax, line));

                    }
                    if (GetValue("buy_sell", line) == "S")
                    {                        
                        Amount = Amount - TotalTax;
                        Quan = Quan * -1;
                    }
                    else
                    {
                        Amount = (Amount + TotalTax) * -1;
                    }
                    
                    try
                    {
                        Updateportfolio(ClientCode, CompanySymbol, Quan);                     

                        //LogBox.AppendText(ClientCode + " : " + Amount + "\n");
                        DailyTransactions DailyTr = new DailyTransactions();


                        DailyTr.TradeDate = DateTime.Parse(GetValue("trade_date", line) + " " + GetValue("trade_time", line));

                        DailyTr.TranId = GetValue("tran_id", line);
                        DailyTr.ExecutionId = ExecID;                        
                        DailyTr.BuySell = GetValue("buy_sell", line);
                        DailyTr.CompanySymbol = CompanySymbol;
                        //DailyTr.Quantity            = Int32.Parse(GetValue("quantity", line));
                        DailyTr.Quantity = Int32.Parse(GetValue("quantity", line));
                        DailyTr.Price = double.Parse(GetValue("price", line));
                        DailyTr.TaxFlag = Int32.Parse(GetValue("tax_flag", line));
                        DailyTr.BrokerIdBuy = GetValue("broker_id_buy", line);
                        DailyTr.BrokerIdSell = GetValue("broker_id_sell", line);
                        DailyTr.BuyingContractNo = Int32.Parse(GetValue("buying_contract_no", line));
                        DailyTr.SellingContractNo = Int32.Parse(GetValue("selling_contract_no", line));
                        DailyTr.ClientCode = ClientCode;
                        DailyTr.ParticipantId = GetValue("participant id", line);
                        DailyTr.ForeignFlag = Int32.Parse(GetValue("foreign_flag", line));
                        DailyTr.Amount = Amount;
                        DailyTr.OrderId = GetValue("order_id", line);
                        DailyTr.Status = Int32.Parse(GetValue("status", line));
                        DailyTr.SettleDate = SettlementDate.Value.Date;

                        DailyTransactionsServices.Add(DailyTr);
                        AddedCount++;
                    }
                    catch (System.Data.OracleClient.OracleException Ora)
                    {
                        if (Ora.Code == 1)
                        {
                            DuplicatedCount++;
                            //LogBox.AppendText("Transaction record already exist.( Exec ID -" + GetValue("execution_id", line) + " )\n");
                        }
                        else
                            MessageBox.Show(Ora.Message, "Error!");

                    }
                    
                    //writing to the DB                   
                  

                }
                
                if(DuplicatedCount != 0)
                {
                    //LogBox.AppendText(DuplicatedCount + " records were already existed.\n");
                    ThreadObj Tobj2 = new ThreadObj();
                    Tobj2.ProgressMax = -1;
                    Tobj2.LogMsg = DuplicatedCount + " records were already existed.\n";
                    Tobj2.increment = false;
                    worker.ReportProgress(1, Tobj2);
                }
                //LogBox.AppendText(AddedCount + " records were added to the database.\n");
                ThreadObj Tobj1 = new ThreadObj();
                Tobj1.ProgressMax = -1;
                Tobj1.LogMsg = AddedCount + " records were added to the database.\n";
                Tobj1.increment = false;
                worker.ReportProgress(1, Tobj1);
                //System.Console.WriteLine("No of records :" + count);
                
              
            }
            catch (Exception fileEx)
            {
                //throw;
                MessageBox.Show(fileEx.Message, "Error");
            }
        }

       
        static String GetValue(String ClmName, String Line)
        {
            String value = "";
            value = Line.Substring(mapOffset[ClmName], mapSize[ClmName]);
            return value.Trim();
        }


        public void ReadCDSTranDataFile()
        {
            int count = 0;
            int AddedCount = 0; 
            try
            {
                List<String> ClientsList = ClientService.GetClientCodeCollection();
                List<String> CDSTable = CDSTranServices.GetCDSTranCollectionDataTable(TrDate.Value.Date);

                string[] lines = System.IO.File.ReadAllLines(CDSDataTxtBox.Text);

                CultureInfo provider = CultureInfo.InvariantCulture;
                progressBar1.Value = 0;
                progressBar1.Maximum = lines.Length;

                SymbolList.Clear();
                SymbolList = SecurityServices.GetSecSymbolList();

                foreach (string line in lines)
                {
                    //System.Console.WriteLine("No of Lines :" + line.Length);

                    count++;
                    
                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {
                        MessageBox.Show("Error in Line " + count + " of the ats2_ttr data file.\n" +
                                       "Please check the file and try again.");
                        return;

                    }       

                    //Trading date has to be matched with the date in the file.
                    if (GetValue("transaction_date", line).CompareTo(TrDate.Value.ToString("ddMMyyyy")) != 0 )
                    {
                        MessageBox.Show("Trading date mismatch", "Error");
                        return;
                    }

                    progressBar1.Increment(1);

                    String JointACNo = GetValue("joint_ac_no", line);
                    if (JointACNo.Length == 1)
                        JointACNo = "0" + JointACNo;

                    String ClientCode = BROKER_CODE + "-" +
                                        GetValue("client_prefix", line) + "-" +
                                        GetValue("client_suffix", line) + "-" +
                                        JointACNo;
                    int Quan = 0;
                    String TranType = "D";

                    if ( int.Parse(GetValue("quantity", line)) < 0  )
                    {
                        Quan = Quan * -1;
                        TranType = "W";
                    }

                    //Console.WriteLine(ClientCode);
                    if (!ClientsList.Contains(ClientCode))
                    {
                        QuickAddClient(ClientCode, BROKER_CODE);
                        ClientsList.Add(ClientCode);
                        //continue;
                    }
                    
                    if (CDSTable.Contains(GetValue("reference", line))   )
                    {
                        continue;
                    }

                    
                    String CompanySymbol = GetValue("company_id", line) + "-" +
                                            GetValue("main_type", line) + "-" +
                                            GetValue("sub_type", line);

                    UpdateSecurity(CompanySymbol); 
                    
                    try
                    {

                        String ExecId = "P" + GetValue("reference", line);

                        DateTime TranDate = DateTime.ParseExact(GetValue("transaction_date", line), "ddMMyyyy", provider);

                        DailyTransactions DTransac =
                            DailyTransactionsServices.GetDailyTransactionsByExecIdAndDate(ExecId, TranDate);
                  
                        if(DTransac != null)
                        {
                            LogBox.AppendText("Transaction record already exist. Line No." + count + "\n");
                            continue;
                        }
                        Updateportfolio(ClientCode, CompanySymbol, Int32.Parse(GetValue("quantity", line)));

                        CDSTran trans = new CDSTran();

                        trans.transaction_date = TranDate;
                        trans.reference = GetValue("reference", line);
                        trans.company_symbol = CompanySymbol;
                        trans.client_code = ClientCode;
                        trans.transaction_type = GetValue("transaction_type", line);
                        trans.transaction_desc = GetValue("transaction_desc", line);
                        trans.quantity = Int32.Parse(GetValue("quantity", line));
                        trans.trade_date = GetValue("trade_date", line);
                        trans.broker_code = BROKER_CODE;

                        CDSTranServices.Add(trans);
                        AddedCount++;
                    }
                    catch (System.Data.OracleClient.OracleException Ora)
                    {
                        if (Ora.Code == 1)
                            LogBox.AppendText("Transaction record already exist.( Reference -" + GetValue("reference", line) + " )\n");
                        else
                            MessageBox.Show(Ora.Message, "Error!");

                    }
                    
                    //LogBox.AppendText(ClientCode + "\n");                                        
                }
                LogBox.AppendText("CDS_Tran - " + AddedCount + " records were added to the database.\n");
                
            }
            catch (Exception fileEx)
            {
                MessageBox.Show(fileEx.Message);
            }

        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }


        private void button1_Click_2(object sender, EventArgs e)
        {
           
        }



        private void button2_Click(object sender, EventArgs e)
        {
                   

        }

        private void TrUpload_Click(object sender, EventArgs e)
        {
            LogService.Add(101, Program.currentUser.UserName,
                "Uploading ats2_ttr and trsum files(Trade Date :"+TrDate.Value.ToShortDateString() +")"); 
            progressBar1.Value = 0;

            if (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();
            }
        }


        private void LogBox_TextChanged(object sender, EventArgs e)
        {

        }

        private void button4_Click(object sender, EventArgs e)
        {
            LogService.Add(101, Program.currentUser.UserName,
               "Uploading CDS_Tran and CDS_Regi files(Trade Date :" + TrDate.Value.ToShortDateString() + ")"); 
            ReadClientHdrFile(CDSClientHdrFile, 3);
            ReadCDSClientDataFile();

            ReadTradeHdrFile(CDSTranHdrFile, 3);
            ReadCDSTranDataFile();
        }

        private void TrCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void AtsDataTxtBox_TextChanged(object sender, EventArgs e)
        {

        }


        private void UpdateSecurity(String CompanySymbol)
        {
            //Security SecObj = SecurityServices.GetSecurityBySymbol(CompanySymbol);

            if (!SymbolList.Contains(CompanySymbol))
            {
                try
                {
                    Security SecObj = new Security();
                    SecObj.Name = "";
                    SecObj.Symbol = CompanySymbol;
                    SecObj.MarketValue = 0;
                    SecObj.MarginPercentage = 100;
                    SecurityServices.Add(SecObj);

                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Database Error", "Error");
                    return;
                }

                SymbolList.Add(CompanySymbol);
            }

        }
   

        private void Updateportfolio(String ClientCode,String CompanySymbol, int Quantity)
        {
            Portfolio ClPort = PortfolioServices.GetPortfolioByCodeAndSymbol(ClientCode, CompanySymbol);

            if (ClPort == null)
            {
                ClPort = new Portfolio();
                ClPort.Code = ClientCode;
                ClPort.Symbol = CompanySymbol;     
                ClPort.Quantity = Quantity + ClPort.Quantity;
                
                PortfolioServices.Add(ClPort);
            }
            else
            {
                ClPort.Quantity = ClPort.Quantity + Quantity;
                if (ClPort.Quantity == 0)
                {
                    PortfolioServices.Delete(ClientCode, CompanySymbol);
                }
                else
                {
                    PortfolioServices.Update(ClPort);
                }
                

            }    

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            
        }
        
        void ReadTrsumFile()
        {
            try
            {
                string[] lines = System.IO.File.ReadAllLines(TrsumFile.Text);
                int count = 0;
                int AddedCount = 0;

                progressBar1.Value = 0;
                progressBar1.Maximum = lines.Length;

                String TempComSymbol = "";
                String description = "";
                Double Price = 0.0;
                String CompanySymbol = "";

                bool IsEnd = false;

                Double ClosingPrice = 0.0;
                foreach (string line in lines)
                {
                    count++;
                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {
                       // MessageBox.Show("Error in Line " + count + " of the ats2_ttr data file.\n" +
                        //               "Please check the file and try again.");
                        if (GetValue("description", line) == "... SPECIAL LOTS ...")
                        {
                            IsEnd = true;
                        }
                        else
                        {
                            LogBox.AppendText("Length mismatch in line No." + count + " of the trsum file.\n");
                            continue;
                        }
                        

                    }

                    if (!IsEnd)
                    {

                       Price = Double.Parse(GetValue("price1", line) + "." + GetValue("price2", line));

                        //Trading date has to be matched with the date in the file.
                        if (GetValue("trade_date", line).CompareTo(TrDate.Value.ToString("yyyyMMdd")) != 0)
                        {
                            MessageBox.Show("Trsum - Trading date mismatch", "Error");
                            return;
                        }

                        progressBar1.Increment(1);
                        CompanySymbol = GetValue("company_id", line) + "-" +
                                                                    GetValue("main_type", line) + "-" +
                                                                    GetValue("sub_type", line);

                    }
                    else
                    {
                        CompanySymbol = "End";        
                    }
                    //UpdateSecurity(CompanySymbol);//////////////////////////////

                    if (TempComSymbol == "")
                    {
                        TempComSymbol = CompanySymbol;

                    }
                

                    if (CompanySymbol == TempComSymbol )
                    {
                        ClosingPrice = Price;
                        description = GetValue("description", line);

                    }
                    else
                    {
                        Security Share = SecurityServices.GetSecurityBySymbol(TempComSymbol);             
                        Double MktVal = ClosingPrice;
                        if (Share == null)
                        {                            
                            Share = new Security();
                            Share.Symbol = TempComSymbol;
                            Share.Name = description;
                            Share.MarketValue = double.Parse(MktVal.ToString());
                            Share.MarginPercentage = 100;
                            SecurityServices.Add(Share);

                        }
                        else
                        {
                            if (Share.Name == "")
                            {
                                Share.Name = description;
                            }
                            Share.MarketValue = double.Parse( MktVal.ToString());
                            
                            SecurityServices.Update(Share);
                            
                        }
                        if (IsEnd)
                            break;

                        //MessageBox.Show(" " + TempComSymbol + " : " + TotalTurnover/TotalQuantity);
                        
                        TempComSymbol = CompanySymbol;
                        ClosingPrice = Price;
                        description = GetValue("description", line);
                    }


                }
                LogBox.AppendText("Market summary update done !\n");
                //System.Console.WriteLine("No of records :" + count);


            }
            catch (Exception fileEx)
            {
                //throw;
                MessageBox.Show(fileEx.Message, "Error");
            }
        }



        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {            
            ReadTradeHdrFile(TrHdrFile, 6);
            ReadTradeFile("All", sender);

        }

        private void AtsBrw_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    AtsDataTxtBox.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message, "Error");
                }
            }

        }


        public void ReadClientHdrFile(String FilePath, int StartRow)
        {
            try
            {
                mapOffset.Clear();
                mapSize.Clear();
                string[] lines = System.IO.File.ReadAllLines(FilePath);
                int count = 0;
                int Offset = 0;
                System.Console.WriteLine("No of Lines :" + lines.Length);
                foreach (string line in lines)
                {
                    count++;
                    if (count < StartRow)
                        continue;

                    String ClmName = line.Substring(0, 27).Trim();
                    String size = line.Substring(39, 3);
                    int iSize = 0;
                    try
                    {
                        iSize = Int16.Parse(size);

                    }
                    catch (Exception ee)
                    {
                        continue;
                    }
                    mapSize.Add(ClmName, iSize);
                    mapOffset.Add(ClmName, Offset);

                    Console.WriteLine(ClmName + " " + iSize + " " + Offset);
                    Offset = iSize + Offset;


                }
                LineWidth = Offset;

                System.Console.WriteLine("No of ele :" + mapOffset.Count() + "   " + count);
            }
            catch (Exception fileEx)
            {
                MessageBox.Show(fileEx.Message);
            }

        }

        private void button5_Click(object sender, EventArgs e)
        {

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.InitialDirectory = "D:\\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    NewClientFile.Text = openFileDialog1.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message, "Error");
                }
            }

        }


        public void ReadCDSClientDataFile()
        {
            int count = 0;
            int AddedCount = 0;
            try
            {
                //List<String> ClientsList = ClientService.GetClientCodeCollection();
                //List<String> CDSTable = CDSTranServices.GetCDSTranCollectionDataTable(TrDate.Value.Date);

                string[] lines = System.IO.File.ReadAllLines(NewClientFile.Text);

                CultureInfo provider = CultureInfo.InvariantCulture;
                progressBar1.Value = 0;
                progressBar1.Maximum = lines.Length;

                SymbolList.Clear();
                SymbolList = SecurityServices.GetSecSymbolList();

                foreach (string line in lines)
                {
                    //System.Console.WriteLine("No of Lines :" + line.Length);

                    count++;

                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {
                        MessageBox.Show("Error in Line " + count + " of the CDS_Regi.txt data file.\n" +
                                       "Please check the file and try again.");
                        return;

                    }

                    //Trading date has to be matched with the date in the file.
//                     if (GetValue("transaction_date", line).CompareTo(TrDate.Value.ToString("ddMMyyyy")) != 0)
//                     {
//                         MessageBox.Show("Trading date mismatch", "Error");
//                         return;
//                     }

                    progressBar1.Increment(1);

                    String JointACNo = GetValue("joint_ac_no", line);
                    if (JointACNo.Length == 1)
                        JointACNo = "0" + JointACNo;

                    String ClientCode = BROKER_CODE + "-" +
                                        GetValue("client_prefix", line) + "-" +
                                        GetValue("client_suffix", line) + "-" +
                                        JointACNo;

                    Client NewClient = new Client();      
                    try
                    {               
                         
                        NewClient.Code = ClientCode;
                        NewClient.Title = GetValue("title", line);
                        NewClient.Initials = GetValue("initials", line);
                        NewClient.Surname = GetValue("surname", line);
                        NewClient.OtherNames = GetValue("other_names", line);
                        NewClient.Broker = BROKER_CODE;
                        NewClient.Address_1 = GetValue("address1", line);
                        NewClient.Address_2 = GetValue("address2", line);
                        NewClient.Address_3 = GetValue("address3", line);
                        NewClient.Address_4 = GetValue("country", line);
                        NewClient.RegDate = DateTime.ParseExact(GetValue("date of registration", line), "ddMMyyyy", provider);
                        NewClient.Advisor = "GEN";
                        NewClient.Category = "GEN";

                        ClientService.Add(NewClient);
                        //CDSTranServices.Add(trans);

                        AddedCount++;
                    }
                    catch (System.Data.OracleClient.OracleException Ora)
                    {
                        if (Ora.Code == 1)
                        {
                            LogBox.AppendText("Client already exist.( Client Code -" + ClientCode + " )\n");
                            ClientService.Update(NewClient);
                        }
                        else
                            MessageBox.Show(Ora.Message, "Error!");

                    }

                    //LogBox.AppendText(ClientCode + "\n");
                }
                LogBox.AppendText("CDS_Regi - "+ AddedCount + " clients were added to the database.\n");

            }
            catch (Exception fileEx)
            {
                MessageBox.Show(fileEx.Message);
            }

        }





        void SelectNewClients()
        {

        }

        void WriteNewClientsToFile(StreamWriter file, String AgentCode, ClientCollection MTClients)
        {
            try
            {
                file.WriteLine("#" + "|NewClients");
                foreach (Client NewClient in MTClients)
                {
                    String Clientline = NewClient.Code + "|" +
                                        NewClient.Title + "|" +
                                        NewClient.Initials + "|" +
                                        NewClient.OtherNames + "|" +
                                        NewClient.Surname + "|" +
                                        NewClient.Address_1 + "|" +
                                        NewClient.Address_2 + "|" +
                                        NewClient.Address_3 + "|" +
                                        NewClient.Address_4 + "|" +
                                        NewClient.Broker + "|" +
                                        NewClient.Agent + "|" +
                                        NewClient.Advisor + "|" +
                                        NewClient.RegDate.ToShortDateString() + "|" +
                                        NewClient.MTRegDate.ToShortDateString();

                    file.WriteLine(Clientline);
                }
            }
            catch(Exception exce)
            {
                MessageBox.Show(exce.Message, "Error");
            }

        }

        void WritePortfolioToFile(StreamWriter file, String AgentCode, ClientCollection MTClients)
        {
            try
            {            
                file.WriteLine("#" + "|ClientPortfolio");  
                foreach(Client NewClient in MTClients)
                {
                    PortfolioCollection PortfolioTable = PortfolioServices.GetPortfolioCollectionByCode(NewClient.Code);
                    foreach(Portfolio CliPortfolio in PortfolioTable)
                    {
                        String PortLine = CliPortfolio.Code + "|" +
                                        CliPortfolio.Symbol + "|" +
                                        CliPortfolio.Quantity;
                        file.WriteLine(PortLine);               
                    }

                }
             }
            catch(Exception exce)
            {
                MessageBox.Show(exce.Message, "Error");
            }


        }
        void WriteAccountBalanceToFile(StreamWriter file, String AgentCode, ClientCollection MTClients)
        {
            try
            {
                file.WriteLine("#" + "|AccountBalance");
                foreach (Client NewClient in MTClients)
                {
                    Double AccBalance = DailyTransactionsServices.GetAccStmBalance(NewClient.Code);
                    String AccBalLine = NewClient.Code + "|" +
                                        AccBalance.ToString();
                    file.WriteLine(AccBalLine);                   

                }
            }
            catch (Exception exce)
            {
                MessageBox.Show(exce.Message, "Error");
            }
        }

       

        private void HQDataLoading_Load(object sender, EventArgs e)
        {
            try
            {

                //Holidays = HolidayServices.GetHolidayByDay(TrDate.Value.Date);
                SettlementDate.Value = GetTplus3(TrDate.Value.Date);

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }


        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            
        }

        private DateTime GetTplus3(DateTime CurrentDate)
        {
            int count = 0;
            while (count != 3)
            {
                CurrentDate = CurrentDate.AddDays(1);
                String Value = CurrentDate.DayOfWeek.ToString();
                if (Value != "Saturday" && Value != "Sunday"
                    && HolidayServices.GetHolidayByDay(CurrentDate) == null)
                {
                    count++;
                }
            }

            return CurrentDate;

        }

        private void TrDate_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                SettlementDate.Value = GetTplus3(TrDate.Value.Date);

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }

        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            ThreadObj ThrObj = e.UserState as ThreadObj;
            if (ThrObj.ProgressMax != -1)
            {
                progressBar1.Maximum = ThrObj.ProgressMax;
                
            }
            if (ThrObj.increment == true)
            {
                progressBar1.Increment(1);
                return;
            }
            if(ThrObj.LogMsg != "")
            {
                LogBox.AppendText(ThrObj.LogMsg);
            }


        }

        private void FoldetBrwsBtn_Click(object sender, EventArgs e)
        {
            
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBar1.Value = 0;
            //ReadTradeHdrFile(TrsumHdr, 3); //Commented to reading the market value from Ins_Sect_Stat file
            ReadTradeHdrFile(Ins_Sect_Stat, 3);
            ReadInsSectFile();
            LogBox.AppendText("Data loading - ended\n");
            progressBar1.Value = 0;


        }



        private void QuickAddClient(String ClientCode, String BrokerCode)
        {
            try
            {
                Client NewClient = new Client();

                NewClient.Code = ClientCode;
                NewClient.Broker = BrokerCode;
                NewClient.RegDate = DateTime.Now.Date;
                NewClient.Advisor = "GEN";
                NewClient.Category = "GEN";

                ClientService.Add(NewClient);
                //CDSTranServices.Add(trans);

            }
            catch (System.Data.OracleClient.OracleException Ora)
            {
                if (Ora.Code == 1)
                {
                    //LogBox.AppendText("Client already exist.( Client Code -" + ClientCode + " )\n");
                }
                else
                    MessageBox.Show(Ora.Message, "Error!");

            }

        }


        void ReadInsSectFile()
        {
            try
            {
                string[] lines = System.IO.File.ReadAllLines(TrsumFile.Text);
                int count = 0;
                int AddedCount = 0;

                progressBar1.Value = 0;
                progressBar1.Maximum = lines.Length;

                String TempComSymbol = "";
                String description = "";
                Double Price = 0.0;
                String CompanySymbol = "";

                bool IsEnd = false;

                Double ClosingPrice = 0.0;
                foreach (string line in lines)
                {
                    
                    //Checking the length of a line
                    if (line.Length != LineWidth)
                    {
                        continue;
                    }


                    Price = Double.Parse(GetValue("closing_price", line));

                    //Trading date has to be matched with the date in the file.
                    if (GetValue("trade_date", line).CompareTo(TrDate.Value.ToString("ddMMyyyy")) != 0)
                    {
                        MessageBox.Show("Ins_Sect_Stat - Trading date mismatch", "Error");
                        return;
                    }

                    progressBar1.Increment(1);
                    CompanySymbol = GetValue("symbol", line);
                    CompanySymbol = CompanySymbol.Replace(" ", "");


                        
                    description = GetValue("description", line);


                    Security Share = SecurityServices.GetSecurityBySymbol(CompanySymbol);
                    Double MktVal = ClosingPrice;
                    if (Share == null)
                    {
                        Share = new Security();
                        Share.Symbol = CompanySymbol;
                        Share.Name = description;
                        Share.MarketValue = Price;
                        Share.MarginPercentage = 100;
                        SecurityServices.Add(Share);

                    }
                    else
                    {
                        Share.Name = description;                            
                        Share.MarketValue = Price;

                        SecurityServices.Update(Share);

                    }
                    count++;

                }
                if (count == 0)
                {
                    LogBox.AppendText("Market summary update failed!. Check Ins_Sect_Stat file.\n");
                }
                else
                {
                    LogBox.AppendText("Market summary update done !\n");
                }
                
                //System.Console.WriteLine("No of records :" + count);


            }
            catch (Exception fileEx)
            {
                //throw;
                MessageBox.Show(fileEx.Message, "Error");
            }
        }



    }
}


public class ThreadObj
{
    public int ProgressMax {get;set;}
    public string LogMsg { get; set; }
    public bool increment { get; set; }

    public ThreadObj()
    {
        ProgressMax = 0;
        LogMsg = "";
        increment = false;
    }

}